<template>
	<view class="container">
		<web-view :src="url" id="myWebView" @message="handleMessage"></web-view>
		<!-- 授权组件 -->
        <authorize @onLoadFun="onLoadFun" ref="auth" :isAuto="false" :iShidden="iShidden" :isGoIndex="true" />
	</view>
	
</template>



<script>
let app = getApp()
import authorize from "@/component/authorize/authorize.vue";
import {
	createOrder,
	getHistoryData,
	getVisaOrderBasicData
} from '../../api/order.js'
export default {
	data() {
		return {
			url: '',
			title: '',
			viewerUrl: '/hybrid/html/web/viewer.html', //H5在线预览
			isInternalSources: true,//是否内部来源  外部来源隐藏标题及操作按钮
			formData: null, // 接收的表单数据
			orderId: '', // 订单ID
		}
	},
	mounted() {
	},
	
	onLoad: function (options) {
		console.log(options)
		let url = ""
		if (options.title != "客服咨询" && options.title != "预览模板") {
			let isCustomH5 = url.indexOf('/allstate')
			options.title = isCustomH5 > -1 ? "资料上传" : ""
			url = decodeURIComponent(options.url)
		}

		// // 监听H5页面发送的消息
		// uni.onWebViewMessage((event) => {
		// 	if (event.data && event.data.action === 'submitDriverCardData') {
		// 		this.formData = event.data.formData;
		// 		// 执行下单操作
		// 		this.createOrder();
		// 	}
		// });
		if (options.title == "客服咨询") {
			let cinfo = options.cinfo
			let key = options.key
			url = `https://cschat.cloud.alipay.com/index.htm?tntInstId=vG2_nJei&scene=SCE01311051&cinfo=${encodeURIComponent(cinfo)}&key=${encodeURIComponent(key)}`
			console.log(url)

		}
		else {
			url = decodeURIComponent(options.url)
		}
		this.setData({
			title: options.title,
			isInternalSources: options.isInternalSources || true
		})
		//设置标题
		uni.setNavigationBarTitle({
			title: this.title
		});

		if (this.title == '预览模板') {
			// #ifdef H5
			this.url = `${this.viewerUrl}?file=${url}`;
			// #endif

			// 在安卓和ios手机上  判断是手机系统：安卓，使用pdf.js
			// #ifdef APP-PLUS
			if (plus.os.name === 'Android') {
				this.url = `${this.viewerUrl}?file=${url}`;
			}
			// ios，直接访问pdf所在路径
			else {
				this.url = url;
			}
			// #endif
		} else {
			// url = url.replace('https://h5.aavisa.com','http://localhost:8081');
			this.url = url;
		}
		


	},
	onReady() {
		if (this.isInternalSources == 'false' || this.isInternalSources == false) {
			document.querySelector('.uni-page-head').style.display = 'none'
			document.querySelector('.uni-placeholder').style.display = 'none'
		}
		this.initWebViewContext();
	},
	methods: {
		onLoadFun() {
            // 授权成功后的处理
        },
		// 初始化WebView上下文
		initWebViewContext() {
			let that = this;
			// 使用Uniapp的API创建WebView上下文
			this.webViewContext = my.createWebViewContext('myWebView');
			
		},
		// 处理从H5页面发送的消息
		async handleMessage(event) {
			console.log('收到H5消息:', event.detail);
			if (event.detail && event.detail.name === 'submitDriverCardData') {
				this.formData = event.detail.formData;
				// 执行下单操作
				await this.$refs.auth.setAuthStatus();
                await this.waitForLog();
                if (app.globalData.isLog) {
					this.createOrder();
				}
			} else if (event.detail && event.detail.name === 'requestAlipayAddress') {
				// 处理支付宝地址选择请求
				this.selectAlipayAddress();
			}
		},
		
		// 调用支付宝地址选择功能
		selectAlipayAddress() {
			// #ifdef MP-ALIPAY
			debugger
			console.log("selectAlipayAddress")
			uni.chooseAddress({
				success: (res) => {
					console.log('选择地址成功', res);
					if (!res.userName) {
						return;
					}
					
					// 构建地址信息
					const addressInfo = {
						name: res.name || res.userName,
						phone: res.phone || res.telNumber,
						provinceName: res.provinceName,
						cityName: res.cityName,
						countyName: res.countyName || res.areaName,
						detailInfo: res.detailInfo || res.streetName,
						userName: res.userName,
						telNumber: res.telNumber,
						fullAddress: `${res.provinceName}${res.cityName}${res.countyName || res.areaName}${res.detailInfo || res.streetName}`
					};
					console.log(addressInfo)
					// 将地址信息发送回H5页面
					this.webViewContext.postMessage({
						name: 'alipayAddressSelected',
						addressInfo: addressInfo
					});
				},
				fail: (err) => {
					console.error('选择地址失败', err);
				}
			});
			// #endif
		},
		async waitForLog() {
            for (let index = 0; index < 10; index++) {
                if (!app.globalData.isLog) {
                    await new Promise(resolve => setTimeout(resolve, 2000));
                    console.log("等待登录状态...");
                } else {
                    break;
                }
            }
        },
		// 参照visa/detail.js中的visaDo方法实现下单逻辑
		async createOrder() {
			let that = this
			debugger
			try {
				uni.showLoading({
					title: '请稍后',
					mask: true
				});
				

				// 准备下单数据
				const orderData = {
					// 使用从H5页面接收的数据
					applicants: [{
						applicantName: '待上传',
						docIdx: 0,
						identity: '所有人群', // 默认身份证类型
						identityType:7,
						identity: '身份证'
					}],
					mobile: this.formData.passportData[0].extPhone || '18888888888', // 默认手机号
					proId: '11a3217b983a4c00adc606ef1ca68cd2', // 产品ID
					zfb: '1'
				};
				console.log(orderData,"下单数据")

				// 调用创建订单API
				const app = getApp();
				

				const res = await createOrder(orderData);
				uni.hideLoading();

				if (res && res.data && res.data.orderId) {
					that.orderId = res.data.orderId;

					// 获取passengerid
					// const passengerid = res.data.orderId;
					await that.getVisaOrderBasicData()
					// 将passengerid发送回H5页面
					// my.postMessage({
					// 	data: {
					// 		action: 'orderComplete',
					// 		passengerid: this.passengerId
					// 	}
					// });
					 this.webViewContext.postMessage({ name: 'orderComplete',
							passengerid: this.passengerId });

					// 显示成功提示
					uni.showToast({
						title: '下单成功',
						icon: 'success'
					});
				} else {
					throw new Error('创建订单失败');
				}
			} catch (error) {
				uni.hideLoading();
				console.error('下单失败:', error);

				// 显示错误提示
				uni.showToast({
					title: error.message || '下单失败，请重试',
					icon: 'none'
				});
			}
		},
		async getVisaOrderBasicData() {
			let that = this
			uni.showLoading({
				title: '请稍后',
				mask: true
			})

			let res = await getVisaOrderBasicData(this.orderId)
			uni.hideLoading()
			console.log(res)
			if (res && res.data && res.data.applians && res.data.applians.length > 0) {
				that.setData({
					passengerId: res.data.applians[0].Id
				})
			}
		},
	}
}
</script>

<style scoped></style>
